﻿using FluentFTP;
using System;
using System.Linq;
using System.Text;

namespace Glorysoft.EAP.Core
{
    public class FTPContext
    {
        private static FTPContext context;
        public static FTPContext Instance { get { return context; } }
        public static void Init(string ip, int port, string userName, string password)
        {
            if (context is null)
                context = new FTPContext(ip, port, userName, password);
        }

        private FtpClient client;

        public FTPContext(string ip, int port, string userName = null, string password = null)
        {
            client = new FtpClient(ip, port);
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) client.Credentials = new System.Net.NetworkCredential(userName, password);
            client.AutoConnect();

        }
        public string FindFile(string fileName, string beginRoot)
        {
            foreach (var ftpItem in client.GetListing(beginRoot).OrderBy(o => o.Type))
            {
                if (ftpItem.Type.Equals(FtpObjectType.File) && ftpItem.Name.Equals(fileName))
                    return ftpItem.FullName;
                else if (ftpItem.Type.Equals(FtpObjectType.Directory))
                {
                    var targe = FindFile(fileName, ftpItem.FullName);
                    if (!string.IsNullOrEmpty(targe))
                        return targe;
                }
            }
            return null;
        }
        public byte[] ReadFile(string path)
        {
            client.DownloadBytes(out var fileBytes, path);
            client.Disconnect();
            return fileBytes;
        }
    }
}
